package com.renfei.minevideoplayer.opengl;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import com.renfei.minevideoplayer.R;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * 三角形 Render
 */
public class TrianglesRender implements GLSurfaceView.Renderer {

    private Context context;
    private float[] vertexData = {
            -1.0f, 0.0f,
            1.0f, 0.0f,
            0.0f, 1.0f
    };

    private FloatBuffer vertexBuffer;

    private int program;
    private int av_Position;//attribute  vec4
    private int af_Potion;  //uniform   vec4

    public TrianglesRender(Context context) {
        this.context = context;
        vertexBuffer = ByteBuffer.allocateDirect(vertexData.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        vertexBuffer.put(vertexData).position(0);
    }


    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        program = OpenGLUtil.createProgram(
                OpenGLUtil.loadRawShaderSource(context, R.raw.vertex_shader),
                OpenGLUtil.loadRawShaderSource(context, R.raw.fragment_shader)
        );
        if (program > 0) {
            av_Position = GLES20.glGetAttribLocation(program, "av_Position");
            af_Potion = GLES20.glGetUniformLocation(program, "af_Potion");
        }
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        GLES20.glClearColor(.01f, 0.4f, 0.7f, 1.0f);

        GLES20.glUseProgram(program);
        //设置颜色
        GLES20.glUniform4f(af_Potion,1.0f,1.0f,0.0f,1.0f);

        GLES20.glEnableVertexAttribArray(av_Position);
        GLES20.glVertexAttribPointer(av_Position,2,GLES20.GL_FLOAT,
                false,//坐标是否归一化   如果坐标在-1，1 范围内  则不需要开启归一化
                0,
                vertexBuffer
        );
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,3);
    }
}
